<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace Org\My;
use Think\Model;


class SendSms{
    /**
    * +--------------------------------------------------------------------------
    * 请求发送短信接口，60秒后才能重新发送
    *
    * @param int $tplid 短信模板id
    * @param string $mobile 手机号码
    * @return json
    * +--------------------------------------------------------------------------
    */
    public function sendSms($tpl_id,$mobile){
        // 检查数据库记录 ,是否在 60 秒内已经发送过一次
        
        $Record = M("sms_record");
        $where = array(
            'mobile' => $mobile,
            'tpl_id' => $tpl_id,
        );
        $sms_record = $Record->where($where)->find();
        if( $sms_record && ( (time() - $sms_record['time']) < 60 ) ){
            
            $result = $this->smsReturn('60秒内不能多次发送', 1);           
            return $result;
            
        }
        // 如果60秒内没有发过，则发送验证码短信（6位随机数字）
        $code = mt_rand(100000, 999999);
        $smsConf = array(
            'key'   => C("SEND_SMS_KEY"), //您申请的APPKEY
            'mobile'    => $mobile, //接受短信的用户手机号码
            'tpl_id'    => $tpl_id, //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>'#code#=' . $code //您设置的模板变量，根据实际情况修改 '#code#=1234&#company#=聚合数据'
        );

        //测试阶段，不发短信，直接设置一个“发送成功” json 字符串
        $content = $this->juhecurl(C("SEND_SMS_URL") ,$smsConf, 1); //请求发送短信
        //$content = json_encode(array('error_code'=>0, 'reason'=>'发送成功'));
        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                // 状态为0，说明短信发送成功
                // 数据库存储发送记录,用于处理倒计时和输入验证，首先要删除旧记录
                $Record->where("mobile=" . $mobile)->delete();
                    $data = array(
                        'mobile' => $mobile,
                        'tpl_id'=> $tpl_id,
                        'code'=>$code,
                        'time'=>time()
                    );
                    $Record->data($data)->add();                   
                $result = $this->smsReturn('短信发送成功', 0);
                //echo "短信发送成功,短信ID：".$result['result']['sid'];
            }else{           
                $result = $this->smsReturn('短信发送失败', 1);
                //状态非0，说明失败
                //echo "短信发送失败(".$error_code.")：".$msg;
            }
        }else{          
            $result = $this->smsReturn('短信发送失败', 1);
            //返回内容异常，以下可根据业务逻辑自行修改
            //$result['reason'] = '短信发送失败';
        }
        return $result;
    }
    
    /**
    * +--------------------------------------------------------------------------
    * 检查填写的手机验证码是否填写正确
    * 可以添加更多字段改造成注册、登录等表单
    *
    * @param string $get.verify 验证码
    * @param string $mobile 手机号码
    * @param int $tplid 短信模板ID
    * @param int $code 手机接收到的验证码
    * +--------------------------------------------------------------------------
    */
    public function checkSmsCode($mobile,$tplid,$code){
        //$verify = I("get.verify");
        /*if(!$this->check_verify($verify)){
            $content = array('resultcode'=>1000, 'reason'=>'验证码填写错误');
            echo json_encode($content);
            exit();
        }*/
        // 检查数据库记录，输入的手机验证码是否和之前通过短信 API 发送到手机的一致
        $Record = M("sms_record");
        $where = array(
            'mobile' => $mobile,
            'tpl_id' => $tplid,
            'code' => $code,
        );
        $sms_record = $Record->where($where)->find();
        
        if($sms_record){
            $result = $this->smsReturn('短信验证码核对成功', 0);
            // 处理后面的程序（如继续登录、注册等）
        }else{
            $result = $this->smsReturn('短信验证码错误', 1);
        }
        return $result;
    }
    
   
   
    
    /**
    * +--------------------------------------------------------------------------
    * 通用的“聚合数据”请求接口，返回JSON数据
    *
    * @param string $url 接口地址
    * @param array $params 传递的参数
    * @param int $ispost 是否以POST提交，默认GET
    * @return json
    * +--------------------------------------------------------------------------
    */  
    public function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
              //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }
    
    /**
     * 返回信息
     * @param type $code 错误码
     * @param type $reason 错误信息
     */
    private function smsReturn($reason,$code){
        $result = array(
                    'reason' => $reason,           
                    'error_code' => $code
        );
        return $result;
    }
    
}